//
//  NSObject+KLAutoTracker.m
//  RKLFoundationFrame
//
//  Created by RKL on 2018/2/11.
//  Copyright © 2018年 AppFrameWorkDemo. All rights reserved.
//

#import "NSObject+KLAutoTracker.h"
#import <objc/runtime.h>

static void * klInfoDictionaryPropertyKey = &klInfoDictionaryPropertyKey;


@implementation NSObject (KLAutoTracker)

- (NSDictionary *)klInfoDictionary
{
    return objc_getAssociatedObject(self, klInfoDictionaryPropertyKey);
}

- (void)setKlInfoDictionary:(NSDictionary *)klInfoDictionary
{
    if (klInfoDictionary)
    {
        objc_setAssociatedObject(self, klInfoDictionaryPropertyKey, klInfoDictionary, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
}

- (void)configInfoData:(id)obj
{
    if (nil == obj)
    {
        return;
    }
    if ([obj isKindOfClass:[NSDictionary class]])
    {
        self.klInfoDictionary = obj;
    }
    else
    {
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        
        unsigned count;
        // 获取注册类的属性列表，第一个参数是类，第二个参数是接收类属性数目的变量
        objc_property_t * properties = class_copyPropertyList([obj class], &count);
        
        for (int i = 0; i < count; i++)
        {
            NSString * key = [NSString stringWithUTF8String:property_getName(properties[i])];
            
            if (key.length > 0 && [obj valueForKey:key])
            {
                [dict setObject:[obj valueForKey:key] forKey:key];
            }
        }
        
        free(properties);
        
        if (dict)
        {
            self.klInfoDictionary = dict;
        }
    }
}

@end
